<template>
  <div class="app-container flex flex-sub"
    style="background: none; height: 100%; padding: 1rem">
    <div class="flex flex-sub">
      <el-card shadow="never"
        class="box-card flex-sub"
        style="overflow: auto">
        <div class="div-query">
          <div class="collapse">
            <div class="collapse-header"
              @click="panelActive = !panelActive">
              <i class="collapse-header-icon"
                :class="[
                  panelActive ? 'el-icon-caret-bottom' : 'el-icon-caret-top',
                ]" />
              {{ panelActive ? '隐藏' : '展开' }}查询条件
            </div>
            <div class="collapse-content">
              <el-collapse-transition>
                <div v-show="panelActive">
                  <el-form size="small"
                    label-position="right">
                    <el-row>
                      <el-col :span="10">
                        <el-form-item label="角色名称"
                          label-width="80px">
                          <el-input v-model="queryParams.roleName"
                            :placeholder="$t('table.role.roleName')"
                            clearable
                            class="filter-item search-item" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="14">
                        <el-form-item style="margin-left: 10px">
                          <el-button class="filter-item"
                            type="primary"
                            @click="search"
                            style="margin-right: 10px">
                            {{ $t('table.search') }}
                          </el-button>

                          <el-button class="filter-item"
                            type="info"
                            @click="reset"
                            style="margin-right: 10px">
                            {{ $t('table.reset') }}
                          </el-button>

                          <el-dropdown v-has-any-permission="[
                            'role:add',
                            'role:delete',
                            'role:export',
                          ]"
                            trigger="click"
                            class="filter-item">
                            <el-button>
                              {{ $t('table.more')
                              }}<i class="el-icon-arrow-down el-icon--right" />
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                              <el-dropdown-item v-has-permission="['role:add']"
                                @click.native="add">{{ $t('table.add') }}</el-dropdown-item>
                              <el-dropdown-item v-has-permission="['role:delete']"
                                @click.native="batchDelete">{{ $t('table.delete') }}</el-dropdown-item>
                              <el-dropdown-item v-has-permission="['role:export']"
                                @click.native="exportExcel">{{ $t('table.export') }}</el-dropdown-item>
                            </el-dropdown-menu>
                          </el-dropdown>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </el-collapse-transition>
            </div>
          </div>
        </div>
        <el-table ref="table"
          :key="tableKey"
          v-loading="loading"
          :data="list"
          border
          fit
          size="medium"
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa' }"
          @selection-change="onSelectChange"
          @sort-change="sortChange">
          <el-table-column type="selection"
            align="center"
            width="40px" />
          <el-table-column :label="$t('table.role.roleName')"
            prop="username"
            :show-overflow-tooltip="false"
            align="center"
            min-width="100px">
            <template slot-scope="scope">
              <span>{{ scope.row.roleName }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.role.remark')"
            prop="remark"
            :show-overflow-tooltip="false"
            align="center"
            min-width="200px">
            <template slot-scope="scope">
              <span>{{ scope.row.remark }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.role.createTime')"
            prop="createTime"
            :show-overflow-tooltip="false"
            align="center"
            min-width="120px"
            sortable="custom">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.operation')"
            align="center"
            width="100px"
            class-name="small-padding fixed-width">
            <template slot-scope="{ row }">
              <el-tooltip effect="dark"
                content="编辑"
                placement="top-start">
                <i class="iconfont icon-bianji2 i-edit"
                  @click="edit(row, 'edit')"
                  v-has-permission="['role:update']" />
              </el-tooltip>
              <i class="iconfont icon-fengefu i-fengefu" />
              <el-tooltip effect="dark"
                content="删除"
                placement="top-start">
                <i class="iconfont icon-shanchu i-delete"
                  @click="singleDelete(row, row.name)"
                  v-has-permission="['role:delete']" />
              </el-tooltip>

              <el-link v-has-no-permission="['role:update', 'role:delete']"
                class="no-perm">
                {{ $t('tips.noPermission') }}
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0"
          :total="total"
          :page.sync="pagination.num"
          :limit.sync="pagination.size"
          @pagination="search" />
      </el-card>
    </div>
    <div class="flex flex-direction"
      style="width: 45%; margin-left: 1rem">
      <el-card shadow="never"
        class="box-card flex-sub"
        style="overflow: auto">
        <div slot="header"
          class="clearfix">
          <span>{{
            role.roleId === '' ? '角色管理 ＞新增' : '角色管理 ＞编辑'
          }}</span>
        </div>
        <div>
          <el-form ref="form"
            size="small"
            :model="role"
            :rules="rules"
            label-position="right"
            label-width="100px">
            <el-form-item :label="$t('table.role.roleName')"
              prop="roleName">
              <el-input v-model="role.roleName"
                :readonly="role.roleId === '' ? false : 'readonly'" />
            </el-form-item>
            <el-form-item :label="$t('table.role.remark')"
              prop="remark">
              <el-input v-model="role.remark"
                type="textarea"
                rows="3" />
            </el-form-item>
            <el-form-item :label="$t('table.role.perms')"
              prop="remark">
              <el-tree ref="permsTree"
                :data="permsTree"
                show-checkbox
                accordion
                node-key="id"
                highlight-current
                @check="handleCheckChange" />
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <el-card shadow="never"
        style="height: 60px; border-top: 0">
        <el-row>
          <el-col :span="24"
            style="text-align: right">
            <el-button type="primary"
              :loading="buttonLoading"
              @click="submit">{{
                role.roleId === ''
                ? this.$t('common.add')
                : this.$t('common.edit')
              }}</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import db from '@/utils/localstorage'
import dataTableMixins from '@/mixins/data-table-mixins'
export default {
  name: 'RoleManage',
  components: { Pagination },
  mixins: [dataTableMixins],
  data () {
    return {
      tableKey: 0,
      loading: false,
      buttonLoading: false,
      list: null,
      selection: [],
      total: 0,
      permsTree: [],
      queryParams: {},
      sort: {},
      pagination: {
        size: 10,
        num: 1,
      },
      role: this.initRole(),
      rules: {
        roleName: [
          {
            required: true,
            message: this.$t('rules.require'),
            trigger: 'blur',
          },
          {
            min: 3,
            max: 10,
            message: this.$t('rules.range3to10'),
            trigger: 'blur',
          },
          {
            validator: (rule, value, callback) => {
              if (!this.role.roleId) {
                this.$get(`system/role/check/${value}`).then((r) => {
                  if (!r.data) {
                    callback(this.$t('rules.roleNameExist'))
                  } else {
                    callback()
                  }
                })
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
        remark: {
          max: 50,
          message: this.$t('rules.noMoreThan50'),
          trigger: 'blur',
        },
      },
    }
  },
  mounted () {
    this.fetch()
    this.initMenuTree()
  },
  methods: {
    initRole () {
      return {
        roleId: '',
        roleName: '',
        remark: '',
      }
    },
    initMenuTree () {
      this.$get('system/menu').then((r) => {
        this.permsTree = r.data.data.rows
        console.log(this.permsTree, '树结构')
      })
    },
    onSelectChange (selection) {
      this.selection = selection
    },
    clearSelections () {
      this.$refs.table.clearSelection()
    },
    exportExcel () {
      this.$download(
        'system/role/excel',
        {
          pageSize: this.pagination.size,
          pageNum: this.pagination.num,
          ...this.queryParams,
        },
        `role_${new Date().getTime()}.xlsx`
      )
    },
    edit (row, type) {
      console.log('row=', row)
      this.$refs.form.clearValidate()
      this.role = { ...row }
      this.role.menuIds = this.role.menuIds ? this.role.menuIds.split(',') : []

      this.$nextTick(() => {
        this.role.menuIds.forEach((value) => {
          this.$refs.permsTree.setChecked(value, true, false)
        })
      });

    },
    singleDelete (row) {
      this.$refs.table.toggleRowSelection(row, true)
      this.batchDelete()
    },
    batchDelete () {
      if (!this.selection.length) {
        this.$message({
          message: this.$t('tips.noDataSelected'),
          type: 'warning',
        })
        return
      }
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning',
      })
        .then(() => {
          const roleIds = []
          this.selection.forEach((r) => {
            roleIds.push(r.roleId)
          })
          this.delete(roleIds)
        })
        .catch(() => {
          this.clearSelections()
        })
    },
    delete (roleIds) {
      this.loading = true
      this.$delete(`system/role/${roleIds}`).then(() => {
        this.$message({
          message: this.$t('tips.deleteSuccess'),
          type: 'success',
        })
        this.search()
      })
    },
    submit () {
      console.log('this.$refs.permsTree.getCheckedKeys().join(', ')=', this.$refs.permsTree.getCheckedKeys().join(','))
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.role.roleId) {
            this.role.menuIds = this.role.menuIds.join(',')
            this.role.createTime = this.role.modifyTime = null
            this.$put('system/role', { ...this.role }).then(() => {
              this.buttonLoading = false
              this.$message({
                message: this.$t('tips.updateSuccess'),
                type: 'success',
              })
              this.reset()
              this.clearLimit()
            })
          } else {
            this.role.menuIds = this.role.menuIds.join(',')
            this.$post('system/role', { ...this.role }).then(() => {
              this.buttonLoading = false
              this.$message({
                message: this.$t('tips.createSuccess'),
                type: 'success',
              })
              this.reset()
              this.clearLimit()
            })
          }
        } else {
          return false
        }
      })
    },
    add () {
      this.resetForm()
      this.$message({
        message: this.$t('tips.createTips'),
        type: 'info',
      })
    },
    sortChange (val) {
      this.sort.field = val.prop
      this.sort.order = val.order
      this.search()
    },
    reset () {
      this.resetForm()
      this.queryParams = {}
      this.sort = {}
      this.$refs.table.clearSort()
      this.search()
    },
    resetForm () {
      this.$refs.form.clearValidate()
      this.$refs.form.resetFields()
      this.role = this.initRole()
      this.$refs.permsTree.setCheckedKeys([])
    },
    search () {
      this.resetForm()
      this.fetch({
        ...this.queryParams,
        ...this.sort,
      })
    },
    fetch (params = {}) {
      this.loading = true
      params.pageSize = this.pagination.size
      params.pageNum = this.pagination.num
      this.$get('system/role', { ...params }).then((r) => {
        const data = r.data.data
        this.list = data.rows
        this.total = data.total
        this.loading = false
      })
    },
    clearLimit () {
      db.remove('USER_ROUTER')
      db.remove('PERMISSIONS')
      location.reload()
    },

    handleCheckChange (data, node) {
      console.log('data=', data)
      console.log('node=', node)
      this.role.menuIds = node.checkedKeys;
      node.halfCheckedKeys.forEach((i) => {
        this.role.menuIds.push(i)
      });
    }
  },
}
</script>

<style lang="scss">
.el-tree {
  background: none !important;
  border: none !important;
}
</style>
<style lang="scss" scoped>
@import '../../../../styles/part-custom';
</style>
